const express = require("express");
const { db } = require("../database");
const { ManagerAuth } = require("../middles");
const { validate, validators } = require("../validate");
const { query, findOne } = require("../logic");

const router = express.Router();
router.use(ManagerAuth);

// routes
router
  .get(
    "/",
    validate([validators.limit, validators.offset]),
    async (req, res) => {
      res.send({
        success: true,
        query: await query(
          req,
          "stockOrders a join product b on a.product_id = b.id",
          { fields: "a.*, json_array(b.id, b.name) product" }
        ),
      });
    }
  )
  // 添加入库单
  .post("/", validate([validators.product_id]), async (req, res) => {
    const { product_id, size, color, quantity, date_on, handler } = req.body;
    const results = await db.select(
      "insert into StockOrders (product_id, size, color, quantity, date_on, handler) values (?,?,?,?,?,?)",
      [product_id, size, color, quantity, new Date(date_on), handler]
    );
    // 添加库存信息
    const stock = await db.findOne(
      "select * from Stock where product_id = ? and size = ? and color = ?",
      [product_id, size, color]
    );
    if (stock)
      await db.query("update Stock set quantity = quantity + ? where id = ?", [
        quantity,
        stock.id,
      ]);
    else
      await db.query(
        "insert Stock (product_id, size, color, quantity) values (?, ?, ?, ?);",
        [product_id, size, color, quantity]
      );
    //
    res.send(
      await findOne(
        results.insertId,
        "stockOrders a join product b on a.product_id = b.id",
        {
          fields: "a.*, json_array(b.id, b.name) product",
          wheres: ["a.id = ?"],
        }
      )
    );
  });
const registerRouter = (app) => app.use("/stockOrders", router);
module.exports = { registerRouter };
